package com.tg.service.suzakuEventBus.handler;

import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;
import com.tg.service.eventbus.EventHandler;
import com.tg.service.suzakuEventBus.pojo.BaseTask;
import com.tg.service.suzakuEventBus.pojo.RuntimeEvent;
import com.tg.service.suzakuEventBus.pojo.Tuple;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;


public class TaskEventHandler extends EventBus implements EventHandler<RuntimeEvent>, InitializingBean {

    private static final Logger LOGGER = LoggerFactory.getLogger(TaskEventHandler.class);

    private String eventName;

    private String beanName;

    private List<BaseTask> tasks;

    public String getBeanName() {
        return beanName;
    }

    public void setEventName(String eventName) {
        this.eventName = eventName;
        this.beanName = String.format("%s%s", eventName, this.getClass().getSimpleName());
    }

    public List<BaseTask> getTasks() {
        return tasks;
    }

    public void setTasks(List<BaseTask> tasks) {
        this.tasks = tasks;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (!CollectionUtils.isEmpty(this.tasks)) {
            this.tasks.forEach(this::register);
            String taskNames = String.join("->",
                    this.tasks.stream().map(baseTask -> baseTask.getClass().getSimpleName()).collect(Collectors.toList()));
            LOGGER.info("事件【{}】注册业务链：{}", this.eventName, taskNames);
        } else {
            String msg = String.format("事件【%s】业务链配置异常", this.eventName);
            LOGGER.warn(msg);
            throw new BeanCreationException(msg);
        }
    }

    /**
     * event Handler处理接口
     *
     * @param event
     **/
    @Override
    @Subscribe
    public void handle(RuntimeEvent event) {
        if (!eventName.equalsIgnoreCase(event.getEventName())) {
            return;
        }

        System.out.println("i m " + this.beanName + ":" + event);
        Tuple tuple = new Tuple();
        tuple.setEventName(this.beanName + "-" + event.getEventName());
        this.post(tuple);
    }
}
